#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>
#include <stdlib.h>


//声明全局信号量
sem_t *sem;
//缓冲区
char buffer[100];


void *write_handlen(void * argv)
{
    //向缓冲区写入数据
    strcpy(buffer,"hello word...");
    printf("write向缓冲区写入:%s\n",buffer);
    //释放信号两
    sem_post(sem);
    return NULL;
}


void *read_handlen(void * argv)
{
    //获取信号两
    sem_wait(sem);
    printf("read从缓冲区读出:%s\n",buffer);
    //重置缓冲区
    memset(buffer,0,100);
    return NULL;
}

int main(int argc, char const *argv[])
{
    //给信号量分配空间
    sem = malloc(sizeof(sem_t));
    //初始化信号量
    sem_init(sem,0,0);
    //用来保存线程标识符的变量
    pthread_t write,read;
    //创建两个线程
    pthread_create(&write,NULL,write_handlen,NULL);
    pthread_create(&read,NULL,read_handlen,NULL);

    //等待子线程结束
    pthread_join(write,NULL);
    pthread_join(read,NULL);

    //销毁信号量
    sem_destroy(sem);

    //释放内存
    free(sem);
    return 0;
}
